package com.wdb.modules.quartz.utils;

import com.wdb.modules.quartz.domain.QuartzJob;
import com.wdb.modules.quartz.domain.QuartzLog;
import com.wdb.modules.quartz.mapper.QuartzJobMapper;
import com.wdb.modules.quartz.mapper.QuartzLogMapper;
import com.wdb.modules.quartz.service.QuartzJobService;
import com.wdb.utils.RedisUtils;
import com.wdb.utils.SpringContextHolder;
import com.wdb.utils.StringUtils;
import com.wdb.utils.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.concurrent.Future;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/8/21 星期三 14:37
 */
@Slf4j
public class ExecutionJob extends QuartzJobBean {
  // 此处仅供参考，可根据任务执行情况自定义线程池参数
  private final ThreadPoolTaskExecutor executor = SpringContextHolder.getBean("elAsync");

  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    log.info("executeInternal--{}",executor);
    // 获取任务
    QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
    // 获取spring bean
    QuartzLogMapper quartzLogMapper = SpringContextHolder.getBean(QuartzLogMapper.class);
    QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class);
    RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
    // 生成一个定时任务日志
    QuartzLog quartzLog = new QuartzLog();
    quartzLog.setJobName(quartzJob.getJobName());
    quartzLog.setBeanName(quartzJob.getBeanName());
    quartzLog.setMethodName(quartzJob.getMethodName());
    quartzLog.setParams(quartzJob.getParams());
    quartzLog.setCronExpression(quartzJob.getCronExpression());

    // 执行任务
    long startTime = System.currentTimeMillis();
    String uuid = quartzJob.getUuid();
    try {
      // 执行任务
      QuartzRunnable task =
          new QuartzRunnable(
              quartzJob.getBeanName(), quartzJob.getMethodName(), quartzJob.getParams());
      // SpringContextHolder.getBean(QuartzManage.class).runJobNow(quartzJob);
      Future<Object> future = executor.submit(task);
      future.get();
      // 设置任务执行时间
      String times = String.valueOf(System.currentTimeMillis() - startTime);
      quartzLog.setTime(System.currentTimeMillis() - startTime);
      if (StringUtils.isNotBlank(uuid)) {
        redisUtils.set(uuid, true);
      }
      quartzLog.setIsSuccess(true);
      // 任务状态
      log.info("任务执行成功，任务名称：" + quartzJob.getJobName() + ", 执行时间：" + times + "毫秒");
      // 判断是否存在子任务,如果有就执行子任务
      if (StringUtils.isNotBlank(quartzJob.getSubTask())) {
        String[] tasks = quartzJob.getSubTask().split("[,，]");
        // 执行子任务
        // quartzJobService.executionSubJob(tasks);
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(uuid)) {
        redisUtils.set(uuid, false);
      }
      log.error("任务执行失败，任务名称：{}--{}", quartzJob.getJobName() , e);
      long times = System.currentTimeMillis() - startTime;
      quartzLog.setTime(times);
      // 任务状态 0：成功 1：失败
      quartzLog.setIsSuccess(false);
      quartzLog.setExceptionDetail(ThrowableUtil.getStackTrace(e));
      // 任务如果失败了则暂停
      if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) {
        quartzJob.setIsPause(false);
        // 更新状态
        quartzJobService.updateIsPause(quartzJob);
      }
      // if(quartzJob.getEmail() != null){
      //   EmailService emailService = SpringContextHolder.getBean(EmailService.class);
      //   // 邮箱报警
      //   if(StringUtils.isNoneBlank(quartzJob.getEmail())){
      //     EmailVo emailVo = taskAlarm(quartzJob, ThrowableUtil.getStackTrace(e));
      //     emailService.send(emailVo, emailService.find());
      //   }
      // }
    } finally {
      // 生成日志到数据库
      quartzLogMapper.insert(quartzLog);
    }
  }
}
